package com.gitee.aleenjava.aliyun.mqtt.tools;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author cheng
 */
@Slf4j
public class Tools {

    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    public static String macSignature(String text, String secretKey) {
        Charset charset = Charset.forName("UTF-8");
        String algorithm = "HmacSHA1";
        try {
            Mac mac = Mac.getInstance(algorithm);
            mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
            byte[] bytes = mac.doFinal(text.getBytes(charset));
            return new String(Base64.getEncoder().encode(bytes), charset);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            log.info("macSignature error occur ", e);
        }
        return null;
    }

}
